package com.lagou.edu.mvcframework.pojo;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Interceptors {
    //存储所有的interceptor
    private static Set<Interceptor> interceptors = new HashSet<>();
    //url和interceptor 之间的缓存
    private static Map<String,Interceptor> interptorCache = new HashMap<>();

    /**
     * 存储interceptor
     * @param interceptor
     */
    public static void addInterceptor(Interceptor interceptor){
        interceptors.add(interceptor);
    }

    /**
     * 获取interceptor
     * @param request
     * @return
     */
    public static Interceptor getInterceptor(HttpServletRequest request){
        Interceptor interceptor = null;
        if(interceptors.size()>0) {
            String requestURI = request.getRequestURI();
            Interceptor interceptor1 = interptorCache.get(requestURI);
            if(interceptor1!=null){
                interceptor = interceptor1;
            }else{
                for (Interceptor interceptor2 : interceptors) {
                    if (interceptor2.getPattern().matcher(requestURI).matches()){
                        interceptor = interceptor2;
                        interptorCache.put(requestURI,interceptor);
                    }
                }
            }
        }
        return  interceptor;
    }

}
